package com.uls.found.service.impl;

import java.util.*;

import com.uls.common.core.domain.entity.SysUser;
import com.uls.common.exception.ServiceException;
import com.uls.common.utils.DateUtils;
import com.uls.common.utils.StringUtils;
import com.uls.found.vo.TaskCommentVo;
import com.uls.system.service.ISysUserService;
import com.uls.system.service.impl.SysUserServiceImpl;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uls.found.mapper.EduClaimRecordMapper;
import com.uls.found.domain.EduClaimRecord;
import com.uls.found.service.IEduClaimRecordService;
import org.springframework.transaction.annotation.Transactional;


/**
 * 认领记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-29
 */
@Service
public class EduClaimRecordServiceImpl implements IEduClaimRecordService 
{

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private EduClaimRecordMapper eduClaimRecordMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询认领记录
     * 
     * @param claimId 认领记录主键
     * @return 认领记录
     */
    @Override
    public EduClaimRecord selectEduClaimRecordByClaimId(Integer claimId)
    {
        return eduClaimRecordMapper.selectEduClaimRecordByClaimId(claimId);
    }

    /**
     * 查询认领记录列表
     * 
     * @param eduClaimRecord 认领记录
     * @return 认领记录
     */
    @Override
    public List<EduClaimRecord> selectEduClaimRecordList(EduClaimRecord eduClaimRecord)
    {
        return eduClaimRecordMapper.selectEduClaimRecordList(eduClaimRecord);
    }

    /**
     * 新增认领记录
     * 
     * @param eduClaimRecord 认领记录
     * @return 结果
     */
    @Override
    public int insertEduClaimRecord(EduClaimRecord eduClaimRecord)
    {
        eduClaimRecord.setCreateTime(DateUtils.getNowDate());
        return eduClaimRecordMapper.insertEduClaimRecord(eduClaimRecord);
    }

    /**
     * 修改认领记录
     * 
     * @param eduClaimRecord 认领记录
     * @return 结果
     */
    @Override
    public int updateEduClaimRecord(EduClaimRecord eduClaimRecord)
    {
        eduClaimRecord.setUpdateTime(DateUtils.getNowDate());
        return eduClaimRecordMapper.updateEduClaimRecord(eduClaimRecord);
    }

    /**
     * 批量删除认领记录
     * 
     * @param claimIds 需要删除的认领记录主键
     * @return 结果
     */
    @Override
    public int deleteEduClaimRecordByClaimIds(Integer[] claimIds)
    {
        return eduClaimRecordMapper.deleteEduClaimRecordByClaimIds(claimIds);
    }

    /**
     * 删除认领记录信息
     * 
     * @param claimId 认领记录主键
     * @return 结果
     */
    @Override
    public int deleteEduClaimRecordByClaimId(Integer claimId)
    {
        return eduClaimRecordMapper.deleteEduClaimRecordByClaimId(claimId);
    }

    @Override
    public String importUser(List<EduClaimRecord> eduClaimRecordList, Boolean isUpdateSupport) {

        if (StringUtils.isNull(eduClaimRecordList) || eduClaimRecordList.size() == 0)
        {
            throw new ServiceException("导入客户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for(EduClaimRecord eduClaimRecord:eduClaimRecordList){
            try {

                eduClaimRecordMapper.insertEduClaimRecord(eduClaimRecord);
                successNum++;
                successMsg.append("<br/>" + successNum + "、认领姓名： " +eduClaimRecord.getFoundname() + " 导入成功");
            } catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、认领姓名： " +eduClaimRecord.getFoundname() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    @Override
    @Transactional
    public int submit(Integer claimId, Long userId) {

        EduClaimRecord eduClaimRecord=eduClaimRecordMapper.selectEduClaimRecordByClaimId(claimId);
        String processDefiKey ="myProcess";
       // String processDefiKey ="myWorkProcess";
        Map<String, Object> variables = new HashMap<String,Object>();
        variables.put("inputUser1",userId);
        variables.put("inputUser2",2);
        //没有启动这个流程
        if (eduClaimRecord.getStatus()==0) {
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            eduClaimRecord.setFlowid(Long.parseLong(pi.getProcessInstanceId()));
            eduClaimRecord.setStatus(Long.parseLong("2"));//状态(0-未提交，1-打回，2-审核中，3-已完成）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee(""+userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task=list.get(0);

            taskService.complete(task.getId());

            return  eduClaimRecordMapper.updateEduClaimRecord(eduClaimRecord);
        }
        //流程启动了，打回重新审批，就不用再启动流程（eduClaimRecord.getFlowid()已经创建好的流程id继续审批）
        else{
            Long flowid=eduClaimRecord.getFlowid();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowid)
                    .list();
            Task task=list.get(0);
            taskService.complete(task.getId());
            eduClaimRecord.setStatus(Long.parseLong("2"));//状态(0-未提交，1-打回，2-审核中，3-已完成）
            return  eduClaimRecordMapper.updateEduClaimRecord(eduClaimRecord);
        }
    }

    @Override
    @Transactional
    public List<EduClaimRecord> noFinishTask(long userId, String processDefinitionKey) {

        List<EduClaimRecord> listEduClaimRecord=new ArrayList<EduClaimRecord>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee(""+userId)
                .processDefinitionKey(processDefinitionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("报失申请")) {
               // if (!task.getName().equals("标书审批")) {
                    Long flowid = Long.parseLong(task.getProcessInstanceId());
                    //根据流程id查询mapper的方法
                    EduClaimRecord eduClaimRecord = eduClaimRecordMapper.selectEduClaimRecordFlow(flowid);
                    listEduClaimRecord.add(eduClaimRecord);
                }
            }
        }
        return listEduClaimRecord;
    }




    @Override
    @Transactional
    public List<EduClaimRecord> noFinishTask(long userId, String processDefinitionKey, EduClaimRecord eduClaimRecord) {

        List<EduClaimRecord> listEduClaimRecord=new ArrayList<EduClaimRecord>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee(""+userId)
                .processDefinitionKey(processDefinitionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("报失申请")) {
                //if (!task.getName().equals("标书审批")) {
                    Long flowid = Long.parseLong(task.getProcessInstanceId());
                    eduClaimRecord.setFlowid(flowid);
                    //根据流程id查询mapper的方法
                    EduClaimRecord eduClaimRecord1 = eduClaimRecordMapper.selectEduClaimRecordFlowOther(eduClaimRecord);
                    if (eduClaimRecord!=null){
                        listEduClaimRecord.add(eduClaimRecord);
                    }
                }
            }
        }
        return listEduClaimRecord;
    }

    @Override
    @Transactional
    public void competeTast(Long flowid, Integer agree, Long userId, String comment, Integer claimId) {

        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .processInstanceId("" + flowid)
                .list();
        // 遍历任务列表
        Map<String, Object> params = new HashMap<String, Object>();
        EduClaimRecord eduClaimRecord=eduClaimRecordMapper.selectEduClaimRecordByClaimId(claimId);

        if (list != null && list.size() > 0) {
            for (Task task : list) {

                if (task.getName().equals("第一审批人")) {
               // if (task.getName().equals("副总审批")) {
                    if (agree == 1) {
                        params.put("inputUser3", 105);
                        eduClaimRecord.setStatus(Long.parseLong("2"));//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    } else {
                        eduClaimRecord.setStatus(Long.parseLong("1"));//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    }
                    params.put("pass1", agree);

                } else if (task.getName().equals("第二审批人")) {
               // } else if (task.getName().equals("总经理审批")) {
                    if (agree == 1) {
                        eduClaimRecord.setStatus(Long.parseLong("3"));//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    } else {
                        eduClaimRecord.setStatus(Long.parseLong("1"));//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    }
                    params.put("pass2", agree);
                }

                eduClaimRecordMapper.updateEduClaimRecord(eduClaimRecord);
                // 添加批注时候的审核人，通常应该从session获取
                Authentication.setAuthenticatedUserId(userId.toString());

                // 添加批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);

                // taskId：任务id
                taskService.complete(task.getId(), params);

            }
        }
    }

    @Override
    @Transactional
    public List<EduClaimRecord> finishTask(Long userId, String processDefinitionKey) {

        List<EduClaimRecord> listFinishSudent=new ArrayList<EduClaimRecord>();

        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefinitionKey)
                .processFinished()
                .list();

        if(list!=null&&list.size()>0){
            for(HistoricTaskInstance temp:list){
                if (!temp.getName().equals("报失申请")) {
                //if (!temp.getName().equals("标书审批")) {
                    Long flowid = Long.parseLong(temp.getProcessInstanceId());
                    EduClaimRecord eduClaimRecord = eduClaimRecordMapper.selectEduClaimRecordFlow(flowid);
                    listFinishSudent.add(eduClaimRecord);
                }
            }
        }
        //去重
        List<EduClaimRecord> listFinishTeacher1 = new ArrayList<>(new HashSet<>(listFinishSudent));

        return listFinishTeacher1;
    }

    //查看历史记录
    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flow) {

        List<TaskCommentVo> taskCommentVoList=new ArrayList<>();

        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments(""+flow);

        for (Comment com : list) {
            TaskCommentVo taskCommentVo=new TaskCommentVo();

            taskCommentVo.setMessage(com.getFullMessage());

            SysUser user=userService.selectUserById(Long.parseLong(com.getUserId()));

            taskCommentVo.setUserName(user.getUserName());


            //从历史任务取数据
            List<HistoricTaskInstance> hist= historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(""+flow)
                    .taskId(com.getTaskId())
                    .list();

            if(hist!=null&&hist.size()>0){
                HistoricTaskInstance historicTaskInstance=hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());
            }
            taskCommentVoList.add(taskCommentVo);
        }

        //排序
        List<TaskCommentVo> taskCommentVoListSort=new ArrayList<>();

        for(int i= taskCommentVoList.size()-1;i>=0;i--)

        {
            TaskCommentVo temp=taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);

        }
        return taskCommentVoListSort;
    }
}
